package com.example.vueblog.security;

import com.example.vueblog.entity.security.SelfUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.Set;

/**
 * 权限访问控制
 *
 * @author yushunshun
 * @date 2022/5/28 23:00
 */
@Component("rbacauthorityservice")
public class RbacAuthorityService {
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {

        Object userInfo = authentication.getPrincipal();

        boolean hasPermission = false;

        if (userInfo instanceof SelfUserDetails) {
            SelfUserDetails userDetails = (SelfUserDetails) userInfo;

            //如果是超级管理员则直接返回
            if (userDetails.getIsSupadmin() == 1) {
                return true;
            }

            //获取资源 这里可以去用户所有权限遍历
            Set<String> urls = new HashSet();
            // 这些 url 都是要登录后才能访问，且其他的 url 都不能访问！
            urls.add("/user/testIndex");//application.yml里设置了项目路径，百度一下我就不贴了
            urls.add("/blog/**");
            AntPathMatcher antPathMatcher = new AntPathMatcher();

            for (String url : urls) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }

            return hasPermission;
        } else {
            return false;
        }
    }
}
